package com.example.labSystem.controller;

import com.example.labSystem.entity.Attendance;
import com.example.labSystem.service.IAttendanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 考勤记录表 前端控制器
 * </p>
 *
 * @author 10
 * @since 2024-12-12
 */
@RestController
@RequestMapping("/attendance")
public class AttendanceController {

    @Autowired
    private IAttendanceService attendanceService;

    /**
     * 获取考勤记录（支持分页、日期范围、姓名搜索）
     */
    @Cacheable(value = "attendanceList", key = "'attendanceList_' + #page + '_' + #size + '_' + #startDate + '_' + #endDate + '_' + #searchName")
    @GetMapping("/list")
    public List<Attendance> getAttendanceList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String searchName) {
        return attendanceService.listAttendance(page, size, startDate, endDate, searchName);
    }

    /**
     * 根据用户ID获取考勤记录
     */
    @Cacheable(value = "attendanceList", key = "#userID")
    @GetMapping("/user/{userID}")
    public List<Attendance> getAttendanceByUserID(@PathVariable String userID) {
        return attendanceService.getAttendanceByUserID(userID);
    }

    /**
     * 添加考勤记录（签到）
     */
    @PostMapping("/add")
    @CacheEvict(value = "attendanceList", allEntries = true)  // 清空缓存
    public String addAttendance(@RequestBody Attendance attendance) {
        boolean isSaved = attendanceService.save(attendance);
        return isSaved ? "考勤记录添加成功" : "考勤记录添加失败";
    }

    /**
     * 更新考勤记录（签退/备注）
     */
    @PutMapping("/update/{attendanceID}")
    @CacheEvict(value = "attendanceList", allEntries = true)  // 清空缓存
    public String updateAttendance(@PathVariable String attendanceID, @RequestBody Attendance attendance) {
        System.out.println("kaoqin"+attendanceID+":"+attendance.getCheckOutTime());
        attendance.setAttendanceID(attendanceID);
        boolean isUpdated = attendanceService.updateById(attendance);
        return isUpdated ? "考勤记录更新成功" : "考勤记录更新失败";
    }

    /**
     * 删除考勤记录
     */
    @DeleteMapping("/delete/{attendanceID}")
    @CacheEvict(value = "attendanceList", allEntries = true)  // 清空缓存
    public String deleteAttendance(@PathVariable String attendanceID) {
        boolean isDeleted = attendanceService.removeById(attendanceID);
        return isDeleted ? "考勤记录删除成功" : "考勤记录删除失败";
    }
}
